package cron

import (
	"encoding/json"
	"github.com/alecthomas/log4go"
	"github.com/go-stomp/stomp"
	"log"
	"protobuf/model"
	"protobuf/module/setting"
)

var conn *stomp.Conn
var err error
var Rs = make(chan *model.Result)

const ApplicationJson = "application/json"

func init() {
	conn, err = stomp.Dial("tcp", setting.ACTIVEMQ_HOST_PORT)
	if err != nil {
		log.Fatalf("ActiveMq连接失败: %v", err)
	}
	log.Printf("ActiveMq 连接成功:%v", conn)
	go Producer(Rs)
}

func Producer(rs chan *model.Result) {
	for {
		select {
		case r := <-rs:
			{
				b, _ := json.MarshalIndent(rs, "", "")
				err = conn.Send(
					setting.ACTIVEMQ_TOPIC,
					ApplicationJson,
					b)
				if err != nil {
					r.Status = 2
					model.UpdateResult(r)
					log4go.Error("存储消息队列失败:%v", r)
				} else {
					r.Status = 1
					model.UpdateResult(r)
				}
			}
		}

	}
}
